package com.sumainfor.pc.gmio.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sumainfor.common.Constants;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.PageUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.service.HoEleMeterService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class HoEleMeterSerivceImpl implements HoEleMeterService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HoEleMeterSerivceImpl.class);
    @Autowired
    private HoEleMeterMapper hoEleMeterMapper;
    @Autowired
    private DiChargesDeptMapper diChargesDeptMapper;
    @Autowired
    private SeTenantBillMapper seTenantBillMapper;
    @Autowired
    private ZpcMktFeign zpcMktFeign;
    @Autowired
    private ZzuulFeign zzuulFeign;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private SeBillPayMapper seBillPayMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public JsonResult getHoEleMeterList(Map<String, Object> params) {
        //查询运营部上个月录入的电表信息列表
        System.out.println("执行前的参数:" + params);
        List<Map<String, Object>> gmioList = hoEleMeterMapper.getHoEleMeterList(params);
        //查询运营部上个月录入的电表信息列表
        List<Map<String, Object>> gmioHouList = hoEleMeterMapper.getHoInfoEleMeterList(params);
        List<String> houidList = new ArrayList<String>();//房源编号列表
        for (Map<String, Object> map1 : gmioList) {
            List<Map<String, Object>> EleSumList = new ArrayList<Map<String, Object>>();
            if (map1.get("HouId") != null) {
                houidList.add(map1.get("HouId").toString());
                for (Map<String, Object> map2 : gmioHouList) {
                    if (map2.get("HouId") != null) {
                        if (MapUtils.getString(map1, "HouId").equals(MapUtils.getString(map2, "HouId"))) {
                            EleSumList.add(map2);
                        }
                    }
                }
            }
            map1.put("EleSumList", EleSumList);
        }
        if (houidList.size() == 0) {
            PageUtils pageUtils = new PageUtils();
            if (params.get("EnterMeter").toString().equals("0")) {
                return pageUtils.getJsonResult(new ArrayList<>(), params, 0);
            }
        }

        //加入楼号室号筛选
        if (FieldCheckUtil.isMapFieldNotNull(params, "BuilDing")) {
            List<String> houIdList = zpcMktFeign.getHouseIdListByBuildAndRoom(params);
            houidList.retainAll(houIdList);
        }

        params.put("houidList", houidList);
        System.out.println("运营部查询到的值" + gmioList);
        //查询市场部已签约的房源信息
        params.put("EleType", "1");//只查询电表为费智能电表
        JsonResult marketResult = zpcMktFeign.getHoList(params);
        //保存所有与收费标准关联的编号
        HashSet<Object> conList = new HashSet<Object>();
        //保存公司编号
        HashSet<Object> corList = new HashSet<Object>();
        if (marketResult.get("errorCode").equals("0")) {
            Map<String, Object> marketMap = (Map<String, Object>) marketResult.get("result");
            List<Map<String, Object>> marketList = (List<Map<String, Object>>) marketMap.get("dataList");
            for (Map<String, Object> mktmap : marketList) {
                if (mktmap.get("HouId") != null) {
                    conList.add(mktmap.get("HouId"));
                }
                if (mktmap.get("ComId") != null) {
                    conList.add(mktmap.get("ComId"));
                }
                if (mktmap.get("CorId") != null) {
                    conList.add(mktmap.get("CorId"));
                    corList.add(mktmap.get("CorId"));//保存公司编号传递到网关查询所在市
                }
                if (mktmap.get("MiId") != null) {
                    conList.add(mktmap.get("MiId"));
                }
                if (gmioList != null) {
                    for (Map<String, Object> giomap : gmioList) {
                        if (giomap.get("HouId") != null) {
                            if (MapUtils.getString(giomap, "HouId").equals(MapUtils.getString(mktmap, "HouId"))) {
                                mktmap.putAll(giomap);
                            }
                        }
                    }
                }
            }
            if (corList.size() > 0) {
                params.put("corList", corList);
                JsonResult zuulResult = zzuulFeign.getSysAreaList(params);
                System.out.println("网关查询到的值:" + zzuulFeign);
                List<Map<String, Object>> zuulList = (List<Map<String, Object>>) zuulResult.get("result");
                for (Map<String, Object> zuulmap : zuulList) {
                    conList.add(zuulmap.get("area_id"));
                }
                /*把房源关联收费标准的编号组装*/
                params.put("conList", conList);
                System.out.println("几何参数:" + conList);
                List<Map<String, Object>> list = diChargesDeptMapper.getChargesDeptList(params);
                System.out.println("收费标准集合:" + list);
                for (Map<String, Object> giomap : list) {
                    for (Map<String, Object> mktmap : marketList) {
                        if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "HouId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "ComId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "MiId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "area_id"))) {
                            mktmap.putAll(giomap);
                            continue;
                        } else if (MapUtils.getString(giomap, "ContactId").equals(MapUtils.getString(mktmap, "CorId"))) {
                            mktmap.putAll(giomap);
                            continue;
                        }
                    }
                }
            }
        }
        return marketResult;
    }

    /**
     * 新增电表录入记录
     *
     * @param params
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHoEleMeter(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> HoMap = new HashMap<String, Object>();
                //批次电表记录编号
                String UUID3 = "";
                //电表抄表编号
                String UUID = "";
                int number = 0;
                Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "ElemeId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_ele_meter");
                }});
                //账单支出编号
                String UUID2 = "";
                int number2 = 0;
                Map<String, Object> uuid2 = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "BiId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_tenant_bill");
                }});
                if (uuid != null && (!uuid.get("uuid").toString().equals(""))) {
                    number = Integer.valueOf(uuid.get("uuid").toString());
                }
                if (uuid2 != null && (!uuid2.get("uuid").toString().equals(""))) {
                    number2 = Integer.valueOf(uuid2.get("uuid").toString());
                }
                HoMap.put("by", ContextUtils.getUserId());//操作人
                HoMap.put("Recorder", ContextUtils.getUserId());// 电表记录人编号
                HoMap.put("IfGenerate", 1);//是否生成账单  0.未生成  1.已生成',
                HoMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                HoMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(HoMap);
                HoMap.put("BiType", 2);// 1.房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                HoMap.put("IfAdjust", 0);//当前账单是否可以调整   0.否  1.是,
                HoMap.put("CreateType", "2");//房源详表
                HoMap.put("Create", ContextUtils.getUserId());//账单创建人
                HoMap.put("Status", 1);//账单状态   1.待支付  2.支付完成
                HoMap.put("GenerateTime", HoMap.get("instm"));//账单生成日期
                HoMap.put("BiGenerated", HoMap.get("instm"));//账单生成日期
                HoMap.put("StaTime", HoMap.get("GenerateTime"));//账单周期--开始时间
                HoMap.put("EndTime", ConvertDateTime.dateFormatTimeToStr(ConvertDateTime.FORMAT_ONLY_DATE_EN, ConvertDateTime.addDateTime(ConvertDateTime.getCurDate(), 15, 4)));//账单周期--结束时间
                HoMap.put("LateDay", HoMap.get("EndTime"));//最晚付款时间
                List<Map<String, Object>> listMap = (List<Map<String, Object>>) params.get("data");
                System.out.println("listMAp:" + listMap);
                Calendar now = Calendar.getInstance();
                int month = (now.get(Calendar.MONTH) + 1);
                int num = 0;
                int num2 = 0;
                for (Map<String, Object> dataMap : listMap) {
                    List<Map<String, Object>> arrList = (List<Map<String, Object>>) dataMap.get("arr");
                    for (Map<String, Object> arrMap : arrList) {
                        UUID = ComUtils.getLocalTrmSeqNum("em" + num, number);//电表抄表记录编号
                        UUID2 = ComUtils.getLocalTrmSeqNum("zdzc" + num, number2);//账单编号
                        UUID3 = ComUtils.getLocalTrmSeqNum("ba" + num2, number2);//账单编号
                        arrMap.putAll(HoMap);
                        arrMap.put("ElemeId", UUID);
                        arrMap.put("BatchId", UUID3);
                        hoEleMeterMapper.addHoEleMeter(arrMap);
                        //收入账单
                        arrMap.put("BiId", UUID2);
                        arrMap.put("BiName", month + "月份电费账单");
                        arrMap.put("BiMoney", arrMap.get("BillMoney"));//账单金额
                        arrMap.put("BiName", month + "月份电费账单");
                        arrMap.put("Source", UUID);//来源编号
                        arrMap.put("BillExplain", "电费:" + arrMap.get("BiMoney") + ",均摊电量:" + arrMap.get("perEleNum"));
                        arrMap.put("PubType", 2);//1.水费  2.电费  3.燃气',
                        if (arrMap.get("IfOperaType").toString().equals("0")
                                && arrMap.get("TenId") != null && !arrMap.get("TenId").toString().equals("")) {
                            seTenantBillMapper.addTenantBill(arrMap);
                        }
                        num++;
                    }
                    num2++;
                }
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 服务管家退租时根据房源编号查询上次抄表的数值
     */
    public JsonResult getHoEleMeter(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("HouId") == null) {
            return result.putFailed("服务器繁忙");
        }
        Map<String, Object> map = hoEleMeterMapper.getHoEleMeter(params);
        if (map == null) {
            map = new HashMap<String, Object>();
        } else {
            params.put("BatchId",map.get("BatchId"));
            List<Map<String, Object>> list = hoEleMeterMapper.getHoInfoEleMeter(params);
            if (list != null) {
                map.put("Rests", list);
            }
        }
        result.put(map);
        return result;
    }

    /**
     * 根据电表抄表编号查询一个批次录入的一套房源的表数
     */
    @Override
    public JsonResult getHoEleMeterBatc(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("ElemeId") == null) {
            return result.putFailed("参数不正确");
        }
        List<Map<String, Object>> list = hoEleMeterMapper.getHoEleMeterBatc(params);
        if (list != null) {
            result.put(list);
        } else {
            result.putFailed("服务器繁忙");
        }
        return result;
    }

    /**
     * 租后主管撤回电表账单(账单错误)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult recallHoEleMeter(Map<String, Object> params) {

        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                if (params.get("EleList") == null) {//电表抄表记录集合、账单是否支付完成
                    return result.putFailed("参数不正确");
                }
                //需要撤回的账单集合
                List<Map<String, Object>> EleList = (List<Map<String, Object>>) params.get("EleList");
                //组装修改参数
                Map<String, Object> updateMap = new HashMap<String, Object>();
                updateMap.put("by", ContextUtils.getUserId());//操作人
                updateMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                updateMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(updateMap);
                Map<String, Object> insterMap = new HashMap<String, Object>();
                insterMap.put("by", ContextUtils.getUserId());//操作人
                insterMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                insterMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(insterMap);
                //待支付的账单 不需要修改账单金额
                for (int i = 0; i < EleList.size(); i++) {
                    Map<String, Object> EleMap = EleList.get(i);
                    System.out.println("ElemeId:" + EleMap.get("ElemeId"));
                    System.out.println("BiId:" + EleMap.get("BiId"));
                    System.out.println("IfOperaType:" + EleMap.get("IfOperaType"));
                    params.put("ElemeId", EleMap.get("ElemeId"));//电表抄表编号
                    params.putAll(updateMap);
                    params.put("BiId", EleMap.get("BiId"));//账单编号
                    params.put("delfg", "1");//0正常 1废弃
                    hoEleMeterMapper.updateHoEleDelfg(params);//撤回抄表记录
                    if (EleMap.get("BiId") != null) {
                        params.put("Status", "4");//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）5审核驳回
                        seTenantBillMapper.updateSeTenantDelfg(params);//撤回账单
                    }
                    //新增抄表记录和收入账单
                    EleMap.putAll(insterMap);
                    hoEleMeterMapper.addHoEleMeter(EleMap);
                    if (EleMap.get("IfOperaType").toString().equals("0")) {
                        //是否是整租 0否 1是 2（秘书抄表）
                        seTenantBillMapper.addTenantBill(EleMap);
                    }
                }
                result.putSuccess("操作成功");

            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 租后主管撤回电表账单(审核错误)
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult examHoEleMeter(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                if (params.get("EleData") == null) {//账单信息及账单支付信息
                    return result.putFailed("参数不正确");
                }
                //需要撤回的账单集合
                Map<String, Object> EleData = (Map<String, Object>) params.get("EleData");
                //组装修改参数
                Map<String, Object> updateMap = new HashMap<String, Object>();
                updateMap.put("by", ContextUtils.getUserId());//操作人
                updateMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                updateMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(updateMap);
                Map<String, Object> insterMap = new HashMap<String, Object>();
                insterMap.put("by", ContextUtils.getUserId());//操作人
                insterMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                insterMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(insterMap);
                updateMap.putAll(EleData);
                seTenantBillMapper.updateSeTenantDelfg(updateMap);//撤回账单
                seBillPayMapper.updateSeBillDelfg(updateMap);//撤回支付信息
                insterMap.putAll(EleData);
                seTenantBillMapper.addTenantBill(insterMap);//新增账单
                seBillPayMapper.addSeBillPay(insterMap);//新增支出账单信息
                result.putSuccess("操作成功");
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 获取蜂电智能电表的离线设备列表
     */
    @Override
    public JsonResult reportOfflinehour(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("hour") == null || params.get("index") == null || params.get("size") == null) {
            return result.putFailed("参数不正确");
        }
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                String InteDeviceBeeToken = redisUtils.get("InteDeviceBeeToken");
                //如果获取不到就重新登录
                if (InteDeviceBeeToken == null) {
                    Map<String, Object> loginMap = new HashMap<String, Object>();
                    loginMap.put("version", UUIDUtils.generateShortUuid());//业务流水号UUID
                    loginMap.put("appid", InteDeviceBeeConfig.APP_ID);
                    //登录获取token
                    loginMap = InteDeviceBeeUtil.userLogin(InteDeviceBeeConfig.USERID, InteDeviceBeeConfig.PASS, loginMap);
                    if (loginMap.get("Code").toString().equals("0")) {//0 状态码 请求成功
                        InteDeviceBeeToken = loginMap.get("Expand").toString();
                        //token存到redis中 蜂电token 有效时长一小时
                        redisUtils.set("InteDeviceBeeToken", InteDeviceBeeToken, 3600);
                    } else {
                        return result.putFailed("token获取失败");
                    }
                }
                /*报表 离线设备*/
                Map<String, Object> headParams = new HashMap<String, Object>();
                //设置请求头部信息
                headParams.put("uid", InteDeviceBeeConfig.UID);
                headParams.put("token", InteDeviceBeeToken);
                //获取电表的列表
                Map<String, Object> inteResultMap = InteDeviceBeeUtil.reportOfflinehour(params.get("hour").toString(), params.get("index").toString(), params.get("size").toString(), headParams);
                if (inteResultMap.get("Code") != null && inteResultMap.get("Code").toString().equals("0")) {
                    //电表的列表
                    resultMap.put("Data", inteResultMap.get("Data"));
                    System.out.println("resultMap:" + resultMap);
                    //获取列表的总数
                    Map<String, Object> inteResultMap2 = InteDeviceBeeUtil.reportOfflinehourCount(params.get("hour").toString(), headParams);
                    if (inteResultMap2.get("Code") != null && inteResultMap2.get("Code").toString().equals("0")) {
                        resultMap.put("DataCount", inteResultMap2.get("Data"));
                        System.out.println("resultMap:" + resultMap);
                        result.put(resultMap);
                    } else {
                        result.putFailed("第三方服务器繁忙");
                    }
                } else {
                    result.putFailed("第三方服务器繁忙");
                }
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 获取科技侠的门锁列表
     */
    @Override
    public JsonResult lockList(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("pageNo") == null || params.get("pageSize") == null) {
            return result.putFailed("参数不正确");
        }
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                String DeviceLockToken = redisUtils.get("DeviceLockToken");
                //如果获取不到就重新登录
                if (DeviceLockToken == null) {
                    Map<String, Object> tokenMap = new HashMap<String, Object>();
                    tokenMap.put("client_id", InteDeviceLockConfig.CLIENT_ID);
                    tokenMap.put("client_secret", InteDeviceLockConfig.CLIENT_SECRET);
                    tokenMap.put("grant_type", InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                    tokenMap.put("username", InteDeviceLockConfig.USERNAME);
                    tokenMap.put("password", InteDeviceLockConfig.PASSWORD);
                    tokenMap.put("redirect_uri", InteDeviceLockConfig.REDIRECT_URL);
                    System.out.println("请求科技侠的参数:" + tokenMap);
                    tokenMap = InteDeviceLockUtil.oauth2Token(tokenMap);
                    if (tokenMap.get("access_token") != null) {
                        DeviceLockToken = tokenMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("DeviceLockToken", DeviceLockToken, Long.valueOf(tokenMap.get("expires_in").toString()));
                    } else {
                        return result.putFailed("token获取失败");
                    }
                }
                /*分页获取名下的锁列表*/
                Map<String, Object> lockParams = new HashMap<String, Object>();
                lockParams.put("clientId", InteDeviceLockConfig.CLIENT_ID);
                lockParams.put("accessToken", DeviceLockToken);
                lockParams.put("pageNo", params.get("pageNo"));//页码，从 1 开始
                lockParams.put("pageSize", params.get("pageSize"));//每页数量，默认 20，最大 10000
               lockParams.put("date", InteSameCityUtil.getTimeSign());//当前时间（毫秒数）
//
//                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String sd = sdf.format(new Date(Long.parseLong(InteSameCityUtil.getTimeSign())));
//                lockParams.put("date",sd);//当前时间（毫秒数）



                Map<String, Object> inteResultMap = InteDeviceLockUtil.lockList(lockParams);
                if (inteResultMap.get("list") != null) {
                    List<Map<String,Object>> listDate = (List<Map<String, Object>>) inteResultMap.get("list");
                    for (Map<String,Object> dateMap:listDate) {
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                     String sd = sdf.format(new Date(Long.parseLong(MapUtils.getString(dateMap,"date"))));
                        dateMap.put("date",sd);//当前时间（毫秒数）
                    }


                    result.put(inteResultMap);
                } else {
                    result.putFailed("第三方服务器繁忙");
                }
            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 获取果加的门锁列表
     */
    @Override
    public JsonResult guoJiaLockList(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (params.get("page_size") == null || params.get("current_page") == null) {
            return result.putFailed("参数不正确");
        }
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                String GuoJiaToken = redisUtils.get("GuoJiaToken");
                //如果获取不到就重新登录
                if (GuoJiaToken == null) {
                    Map<String, Object> guoJiaMap = new HashMap<String, Object>();
                    guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                    guoJiaMap.put("version", "1");
                    com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                    //key
                    DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                    //密码
                    bodyJson.put("account", InteGuoJiaConfig.ACCOUNT);
                    bodyJson.put("password", desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                    guoJiaMap = InteGuoJiaUtil.login(params, bodyJson);
                    //返回的token数据
                    Map<String, Object> dataMap = (Map<String, Object>) guoJiaMap.get("data");

                    if (guoJiaMap.get("rlt_code").toString().equals("HH0000")) {//HH0000 、成功
                        GuoJiaToken = dataMap.get("access_token").toString();
                        //token存到redis中
                        redisUtils.set("GuoJiaToken", GuoJiaToken, Long.valueOf(dataMap.get("expires_second").toString()));
                    } else {
                        result.putFailed("token获取失败");
                    }
                }
                /*获取门锁列表*/
                Map<String, Object> headParams = new HashMap<String, Object>();
                headParams.put("s_id", InteGuoJiaUtil.getSid());
                headParams.put("version", "1");
                headParams.put("access_token", GuoJiaToken);
                JSONObject bodyJson = new JSONObject();
                bodyJson.put("page_size", params.get("page_size"));
                bodyJson.put("current_page", params.get("current_page"));
                //获取果加的门锁列表
                Map<String, Object> inteResultMap = InteGuoJiaUtil.loclList(headParams, bodyJson);
                if (inteResultMap.get("rlt_code") != null && inteResultMap.get("rlt_code").toString().equals("HH0000")) {
                   Map<String,Object> dataMap1 = (Map<String, Object>) inteResultMap.get("data");
                    //将时间转化
                    List<Map<String,Object>> rowsList = (List<Map<String, Object>>) dataMap1.get("rows");
                    if (rowsList.size()>0){
                        for (Map<String,Object> rowsMap:rowsList) {
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            String sd = sdf.format(new Date(Long.parseLong(MapUtils.getString(rowsMap,"install_time"))));
                            rowsMap.put("install_time",sd);
                        }
                    }


                    result.put(inteResultMap);
                } else {
                    result.putFailed("第三方服务器繁忙");
                }

            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 查询上一次电表抄表读数()
     * @param params
     * @return
     */
    @Override
    public JsonResult getHouInfoEle(Map<String, Object> params) {
        JsonResult result =new JsonResult();
          String HouInfoIds = MapUtils.getString(params,"HouInfoId");
        Map<String,Object> map1 = hoEleMeterMapper.getHouInfoEle(params);

            if (HouInfoIds.substring(HouInfoIds.length() - 1, HouInfoIds.length()).equals("Z")) {
                return result.put(map1);
            } else {
                if (map1!=null) {
                    Map<String, Object> map2 = new HashMap<>();
                    map2.put("BatchId", map1.get("BatchId"));
                    return result.put(hoEleMeterMapper.getBatchIdList(map2));//查询统一批次下的抄表记录
                }else {
                    return result.put(map1);
                }

            }

    }

}
